﻿# Make sure that powershell.exe.config looks something like this
# <?xml version="1.0"?>
# <configuration>
# 	<startup useLegacyV2RuntimeActivationPolicy="true">
# 		<supportedRuntime version="v4.0.30319"/>
# 		<supportedRuntime version="v2.0.50727"/>
# 	</startup>
# </configuration> 
param( $newRollUpFile )

Write-Host "$($myinvocation.mycommand.name):$newRollUpFile"
$w3wp = @(get-process w3wp -ea SilentlyContinue)
if( $w3wp.Count -gt 0 )
{ 
	foreach( $w3wpProcess in $w3wp )
	{
		$w3wpProcess.Kill() 
	}
	Write-Host "$($myinvocation.mycommand.name):Killed w3wp processes"
}

# You must run DevEnv as admin
$rollUpFile = @(gci "$env:WinDir\Microsoft.NET\" -include $(Split-Path $newRollUpFile -Leaf) -r -ea SilentlyContinue)
if( $rollUpFile.Count -gt 0 )
{
	foreach( $file in $rollUpFile )
	{
		$file.Delete()
	}
	Write-Host "$($myinvocation.mycommand.name):Temporary ASP.NET files RollUp files deleted"
}

# Assume that you are on a Tfs app-tier box (trick: Read x64 registry value from a 32 bit app)
try
{
	$localKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry64)
	$localKey = $localKey.OpenSubKey("Software\Microsoft\TeamFoundationServer\10.0\InstalledComponents\ApplicationTier");
	$tfsInstallPath = $localKey.GetValue("InstallPath").ToString()
	Write-Host "$($myinvocation.mycommand.name):Tfs is installed at $tfsInstallPath"
	$rollUpFile = gci $(Join-Path $tfsInstallPath "Web Services\bin\Plugins") -include $(Split-Path $newRollUpFile -Leaf) -r
	if( $rollUpFile )
	{
		$rollUpFile.Delete()
	}
	copy $newRollUpFile $(Join-Path $tfsInstallPath "Web Services\bin\Plugins")
	copy  $newRollUpFile.Replace("dll","pdb") $(Join-Path $tfsInstallPath "Web Services\bin\Plugins")
}
catch [System.Exception]
{
	Write-Host "Exception caught (You're probably missing a .NET 4 config entry in powershell.exe.config):" + $_
}
